package com.letfox.ad.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.letfox.ad.model.ADApp;
import com.letfox.ad.model.ADAppDevice;
import com.letfox.ad.model.ADAppGeo;
import com.letfox.ad.model.ADAppJson;
import com.letfox.ad.model.ADAppNetwork;
import com.letfox.ad.model.ADArray;
import com.letfox.ad.model.ADPlan;
import com.letfox.ad.model.ADPos;
import com.letfox.ad.model.ADReptRecord;
import com.letfox.ad.model.ADServingMaterial;
import com.letfox.ad.model.ErrorConstants;
import com.letfox.ad.model.UtilConstants;
import com.letfox.ad.service.ADAppDeviceService;
import com.letfox.ad.service.ADAppGeoService;
import com.letfox.ad.service.ADAppNetworkService;
import com.letfox.ad.service.ADAppService;
import com.letfox.ad.service.ADAppSynthesizeService;
import com.letfox.ad.service.ADPlanService;
import com.letfox.ad.service.ADPosService;
import com.letfox.ad.service.ADReptRecordService;
import com.letfox.ad.service.relation.ADColScreService;
import com.letfox.ad.util.ADUtil;
import com.letfox.ad.util.DESUtil;
import com.letfox.common.util.JacksonUtil;
import com.letfox.common.util.MD5Util;

@Service
public class ADAppSynthesizeServiceImpl implements ADAppSynthesizeService {
	
	@Autowired
	private ADAppService adAppService;
	@Autowired
	private ADAppDeviceService adAppDeviceService;
	@Autowired
	private ADAppGeoService adAppGeoService;
	@Autowired
	private ADAppNetworkService adAppNetworkService;
	@Autowired
	private ADPosService adPosService;
	@Autowired
	private ADColScreService adColScreService;
	@Autowired
	private ADReptRecordService adReptRecordService;
	@Autowired
	private ADPlanService adPlanService;
	
	
	@Override
	@Transactional(rollbackFor = Exception.class) 
	public String saveRequest(String params)  throws Exception{
		ADAppDevice adAppDevice=null;
		ADAppGeo adAppGeo=null;
		ADAppNetwork adAppNetwork=null;
		ADPos adPos=null;
		ADAppJson adAppJson=new ADAppJson();
		int value=0;
		int width=0;
		int height=0;
		String token=null;
		String timestamp=null;
		String pos_id=null;
		String app_id=null;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		System.out.println(df.format(new Date())+"：开始解析json");
		String request_json=params;
		try {	
			//打印数据
//			System.out.println("数据解压之后: "+request_json);
			if (request_json==null) 
				return "{\"ret\":\""+ErrorConstants.MISSING_REQUEST+"\",\"msg\":\"\"}";
			JSONObject jsonObject = JSON.parseObject(request_json);
			token=jsonObject.getString("token");
			if (token==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_TOKEN+"\",\"msg\":\"\"}";
			timestamp=jsonObject.getString("timestamp");
			if (timestamp==null){
				return "{\"ret\":\""+ErrorConstants.MISSING_TIMESTAMP+"\",\"msg\":\"\"}";
			}
			//检测时间戳
			//当前系统时间戳
			Date date=new Date();                                                                                      
			if ((date.getTime()-Long.parseLong(timestamp))/1000 > UtilConstants.REQUSTMAXDURATION) {
				return "{\"ret\":\""+ErrorConstants.TIMEOUT_REQUEST+"\",\"msg\":\"\"}";
			}
			String api_version=jsonObject.getString("api_version");
			if (api_version==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_API_VERSION+"\",\"msg\":\"\"}";
			//app
			String appJson=jsonObject.getString("app");
			if (appJson==null) 
				return "{\"ret\":\""+ErrorConstants.MISSING_APP_INFO+"\",\"msg\":\"\"}";
			JSONObject appObject = JSON.parseObject(appJson);
			app_id=appObject.getString("app_id");
			if (app_id==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_APP_ID+"\",\"msg\":\"\"}";
			System.out.println(df.format(new Date())+"：完成请求解析");
			//=====
			//检查APPID
			//======
			ADApp adApp=checkAppId(app_id);
			if(adApp==null)
				return "{\"ret\":\""+ErrorConstants.ERROR_APP_ID+"\",\"msg\":\"\"}";
			//=====
			//检查token
			if (!token.equals(MD5Util.MD5(adApp.getAdAppId()+adApp.getAdAppKey()+timestamp))) 
				return "{\"ret\":\""+ErrorConstants.ERROR_TOKEN+"\",\"msg\":\"\"}";
			
			String package_nam=appObject.getString("package_name");
			if (package_nam==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_PACKAGE_NAME+"\",\"msg\":\"\"}";
			if (!adApp.getPackageName().equals(package_nam))
				return "{\"ret\":\""+ErrorConstants.ERROR_PACKAGE_NAME+"\",\"msg\":\"\"}";
			String app_version=appObject.getString("app_version");
			if (app_version==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_APP_VERSION+"\",\"msg\":\"\"}";
			if (!adApp.getAppVersion().equals(app_version)) 
				return "{\"ret\":\""+ErrorConstants.ERROR_APP_VERSION+"\",\"msg\":\"\"}";
			
			//ad_position
			String posJson=jsonObject.getString("ad_pos");
			if (posJson==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_POS+"\",\"msg\":\"\"}";
			JSONObject posObject = JSON.parseObject(posJson);
			pos_id=posObject.getString("pos_id");
			if (pos_id==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_POS_ID+"\",\"msg\":\"\"}";
			//检查posid
			adPos=checkPosId(app_id, pos_id);
			if (adPos==null) 
				return "{\"ret\":\""+ErrorConstants.ERROR_POS_ID+"\",\"msg\":\"\"}";
			String posWidth=posObject.getString("width");
			if (posWidth==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_WIDTH+"\",\"msg\":\"\"}";
			if (!posWidth.matches("\\d+"))
				return "{\"ret\":\""+ErrorConstants.ERROR_WIDTH+"\",\"msg\":\"\"}";
			String posHeight=posObject.getString("height");
			if (posHeight==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_HEIGHT+"\",\"msg\":\"\"}";
			if (!posHeight.matches("\\d+"))
				return "{\"ret\":\""+ErrorConstants.POS_ERROR_HEIGHT+"\",\"msg\":\"\"}";
			String ad_count=posObject.getString("ad_count");
			if (ad_count==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_AD_COUNT+"\",\"msg\":\"\"}";
			if (!ad_count.matches("\\d+"))
				return "{\"ret\":\""+ErrorConstants.ERROR_AD_COUNT+"\",\"msg\":\"\"}";
			String deeplink=posObject.getString("deeplink");
			if (deeplink==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_DEEPLINK+"\",\"msg\":\"\"}";
			if (!deeplink.matches("[0-1]"))
				return "{\"ret\":\""+ErrorConstants.ERROR_DEEPLINK+"\",\"msg\":\"\"}";
			String render_type=posObject.getString("render_type");
			if (render_type==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_RENDER_TYPE+"\",\"msg\":\"\"}";
			if (!render_type.equals("1"))
				return "{\"ret\":\""+ErrorConstants.ERROR_RENDER_TYPE+"\",\"msg\":\"\"}";
			System.out.println(df.format(new Date())+"：完成app与pos解析");
			//device
			String deviceJson=jsonObject.getString("device");
			if (deviceJson==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_APP_VERSION+"\",\"msg\":\"\"}";
			JSONObject deviceObject = JSON.parseObject(deviceJson);
			String device_type=deviceObject.getString("device_type");
			if (device_type==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_DEVICE_TYPE+"\",\"msg\":\"\"}";
			int deviceInt=Integer.parseInt(device_type);
			if (!(deviceInt>-1 && deviceInt<8))
				return "{\"ret\":\""+ErrorConstants.ERROR_DEVICE_TYPE+"\",\"msg\":\"\"}";
			String os_type=deviceObject.getString("os_type");
			if (os_type==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_OS_TYPE+"\",\"msg\":\"\"}";
			if (!(os_type.equals("android") || os_type.equals("ios")))
				return "{\"ret\":\""+ErrorConstants.ERROR_OS_TYPE+"\",\"msg\":\"\"}";
			String os_version=deviceObject.getString("os_version");
			if (os_version==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_OS_VERSION+"\",\"msg\":\"\"}";
			int count=0;
			Pattern p = Pattern.compile("\\.", Pattern.CASE_INSENSITIVE);		
			Matcher m = p.matcher(os_version); 		
			while (m.find()) {			
				count++;		
			}	
			if (!(count==3 || count==2 || os_version.equals("unknown"))) 
				return "{\"ret\":\""+ErrorConstants.ERROR_OS_VERSION+"\",\"msg\":\"\"}";
			String model=deviceObject.getString("model");
			if (model==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_MODEL+"\",\"msg\":\"\"}";
			String android_id=deviceObject.getString("android_id");
			if (android_id==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_ANDROID_ID+"\",\"msg\":\"\"}";
			if (!android_id.matches("^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]{6,20})$"))
				return "{\"ret\":\""+ErrorConstants.ERROR_ANDROID_ID+"\",\"msg\":\"\"}";
			String android_id_md5=deviceObject.getString("android_id_md5");
			if (android_id_md5==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_ANDROID_MD5+"\",\"msg\":\"\"}";
			String imei=deviceObject.getString("imei");
			if (imei==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_IMEI+"\",\"msg\":\"\"}";
			if (!ADUtil.checkPhoneImei(imei).equals("0"))
				return "{\"ret\":\""+ErrorConstants.ERROR_IMEI+"\",\"msg\":\"\"}";
			String imei_md5=deviceObject.getString("imei_md5");
			if (imei_md5==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_IMEI_MD5+"\",\"msg\":\"\"}";
			String idfv=deviceObject.getString("idfv");
			if (idfv==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_IDFV+"\",\"msg\":\"\"}";
			if (!idfv.matches("^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]{6,20})$"))
				return "{\"ret\":\""+ErrorConstants.ERROR_IDFV+"\",\"msg\":\"\"}";
			String idfa=deviceObject.getString("idfa");
			if (idfa==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_IDFA+"\",\"msg\":\"\"}";
			if (!idfa.matches("^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]{6,20})$"))
				return "{\"ret\":\""+ErrorConstants.ERROR_IDFA+"\",\"msg\":\"\"}";
	        String deviceWidth=deviceObject.getString("width");	
	        if (!deviceWidth.matches("\\d+")) 
	        	return "{\"ret\":\""+ErrorConstants.ERROR_WIDTH+"\",\"msg\":\"\"}";
	        String deviceHeight=deviceObject.getString("height");	
	        if (!deviceHeight.matches("\\d+")) 
	        	return "{\"ret\":\""+ErrorConstants.ERROR_HEIGHT+"\",\"msg\":\"\"}";
	        String idp=deviceObject.getString("idp");	
	        if (!idp.matches("\\d+")) 
	        	return "{\"ret\":\""+ErrorConstants.ERROR_IDP+"\",\"msg\":\"\"}";
	        String imsi=deviceObject.getString("imsi");
			if (imsi==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_IMSI+"\",\"msg\":\"\"}";
			String mac=deviceObject.getString("mac");
			if (mac==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_MAC+"\",\"msg\":\"\"}";
			String orient=deviceObject.getString("orient");
			if (!(orient.equals("0") || orient.equals("90")))
				return "{\"ret\":\""+ErrorConstants.ERROR_ORIENT+"\",\"msg\":\"\"}";
			String resolution=deviceObject.getString("resolution");
		    if (!resolution.matches("\\d+\\*\\d+")) 
		       return "{\"ret\":\""+ErrorConstants.ERROR_RESOLUTION+"\",\"msg\":\"\"}";
		    System.out.println(df.format(new Date())+"：完成device解析");
			//geo
			String geoJson=jsonObject.getString("geo");
			if (geoJson==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_GEO+"\",\"msg\":\"\"}";
			JSONObject geoObject=JSON.parseObject(geoJson);
			String coordinate_type=geoObject.getString("coordinate_type");
			if (coordinate_type==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_COORD_TYPE+"\",\"msg\":\"\"}";
			if (!coordinate_type.matches("[1-4]"))
				return "{\"ret\":\""+ErrorConstants.MISSING_COORD_TYPE+"\",\"msg\":\"\"}";
			String lat=geoObject.getString("lat");
			if (lat==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_LAT+"\",\"msg\":\"\"}";
			if (!lat.matches("^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*$"))
				return "{\"ret\":\""+ErrorConstants.ERROR_LAT+"\",\"msg\":\"\"}";
			String lon=geoObject.getString("lon");
			if (lon==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_LON+"\",\"msg\":\"\"}";
			if (!lon.matches("^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*$"))
				return "{\"ret\":\""+ErrorConstants.ERROR_LON+"\",\"msg\":\"\"}";
			String coord_time=geoObject.getString("coord_time");
			//对时间戳进行解析
			SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
		    try {
		    	Long time=new Long(coord_time);
				String d = format.format(time);
		    	format.parse(d);
			} catch (Exception e) {
				return "{\"ret\":\""+ErrorConstants.ERROR_COORD_TIME+"\",\"msg\":\"\"}";
			}
			//network
			String networkJson=jsonObject.getString("network");
			if (networkJson==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_NETWORK+"\",\"msg\":\"\"}";
			JSONObject networkObject=JSON.parseObject(networkJson);
			String ip=networkObject.getString("ip");
			if (ip==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_IP+"\",\"msg\":\"\"}";
			if (!ip.matches( "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." +"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." +"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." +"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$"))
				return "{\"ret\":\""+ErrorConstants.ERROR_IP+"\",\"msg\":\"\"}";
			String connect_type=networkObject.getString("connect_type");
			if (connect_type==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_CONNECT_TYPE+"\",\"msg\":\"\"}";
			if (!connect_type.matches("-[1-1]||[1-5]"))
				return "{\"ret\":\""+ErrorConstants.ERROR_CONNECT_TYPE+"\",\"msg\":\"\"}";
			String carrier=networkObject.getString("carrier");
			if (carrier==null)
				return "{\"ret\":\""+ErrorConstants.MISSING_CARRIER+"\",\"msg\":\"\"}";
			if (!carrier.matches("-[1-1]||[0-3]"))
				return "{\"ret\":\""+ErrorConstants.ERROR_CARRIER+"\",\"msg\":\"\"}";
			System.out.println(df.format(new Date())+"：完成geo与network解析");
			//ADAppDevice赋值
			adAppDevice=new ADAppDevice();
			adAppDevice.setDeviceType(device_type);
			adAppDevice.setOsType(os_type);
			adAppDevice.setOsVersion(os_type.getBytes());
			adAppDevice.setVendor(deviceObject.getString("vendor"));
			adAppDevice.setModel(model);
			adAppDevice.setAndroidId(android_id);
			adAppDevice.setAndroidIdMd5(android_id_md5);
			adAppDevice.setImei(imei);
			adAppDevice.setImeiMd5(imei_md5);
			adAppDevice.setAndroidAdId(deviceObject.getString("android_ad_id"));
			adAppDevice.setWidth(Integer.parseInt(deviceWidth));
			adAppDevice.setHeight(Integer.parseInt(deviceHeight));
			adAppDevice.setMac(mac);
			adAppDevice.setIdfa(idfa);
			adAppDevice.setOpenudid(deviceObject.getString("openudid"));
			adAppDevice.setIdp(Integer.parseInt(idp));
			adAppDevice.setImsi(imsi);
			adAppDevice.setIdfv(idfv);
			adAppDevice.setResolution(resolution);
			adAppDevice.setIsroot(Integer.parseInt(deviceObject.getString("isroot")));
			adAppDevice.setOrient(orient);
			adAppDevice.setBtmac(deviceObject.getString("btmac"));
			adAppDevice.setAdAppId(app_id);
			adAppDevice.setCreateTime(new Date());
			adAppDevice.setUpdateTime(new Date());
			adAppDevice.setCreateBy("system");
			adAppDevice.setUpdateBy("system");
			adAppDevice.setDel("0");
			//ADAppGeo赋值
			adAppGeo=new ADAppGeo();
			adAppGeo.setAdAppId(UUID.randomUUID().toString());
			adAppGeo.setCoordinateType(Integer.parseInt(coordinate_type));
			adAppGeo.setLon(Double.parseDouble(lon));
			adAppGeo.setLat(Double.parseDouble(lat));
			adAppGeo.setLocationAccuracy(Double.parseDouble(geoObject.getString("location_accuracy")));
			adAppGeo.setCoordTime(Long.parseLong(coord_time));
			adAppGeo.setAdAppId(app_id);
			adAppGeo.setCreateTime(new Date());
			adAppGeo.setUpdateTime(new Date());
			adAppGeo.setCreateBy("system");
			adAppGeo.setUpdateBy("system");
			adAppGeo.setDel("0");
			//ADAppNetwork赋值
			adAppNetwork=new ADAppNetwork();
			adAppNetwork.setIp(ip);
			adAppNetwork.setCarrier(carrier);
			adAppNetwork.setConnectType(connect_type);
			adAppNetwork.setAdAppId(app_id);
			adAppNetwork.setCreateTime(new Date());
			adAppNetwork.setUpdateTime(new Date());
			adAppNetwork.setCreateBy("system");
			adAppNetwork.setUpdateBy("system");
			adAppNetwork.setDel("0");
			//请求素材
			value=Integer.parseInt(posObject.getString("ad_count"));
			width=Integer.parseInt(posWidth);
			height=Integer.parseInt(posHeight);
		} catch (Exception e) {
			return "{\"ret\":\"1\",\"msg\":\"SYSTEM ERROR\"}";
		}
		try {
			//adAppDevice添加数据库操作
			adAppDeviceService.insert(adAppDevice);
			//adAppGeo添加数据库操作
			adAppGeoService.insert(adAppGeo);
			//adAppNetwork添加数据库操作
			adAppNetworkService.insert(adAppNetwork);
			System.out.println(df.format(new Date())+"：完成请求入库");
			//匹配素材数据
			Map<String, String> map=new HashMap<String, String>();
			map.put("adType", adPos.getAdType());
			map.put("width", width+"");
			map.put("height",height+"");
			map.put("value",value+"");
			List<ADServingMaterial> list=new ArrayList<ADServingMaterial>();
			//打印数据
			System.out.println("查询广告素材条件数据:   "+"width: "+width+" height: "+height+"ad_count: "+value+"adType "+adPos.getAdType());
			//查询素材
			list=adColScreService.MatchingMaterial(map);
			List<ADArray> ad_array=new ArrayList<ADArray>();
			adAppJson.setRet("0");
			System.out.println(df.format(new Date())+"：完成搜索素材");
			if (list.size()>0) {
				if (list.size()<value) {
					adAppJson.setRet(ErrorConstants.NO_ENOUGH_AD);
					adAppJson.setMsg("无足够广告返回");
				}
				//requesetId
				adAppJson.setRequest_id(ADUtil.getRequestId());
				for (int i = 0; i <list.size(); i++) {
					ADServingMaterial adServingMaterial=list.get(i);
					ADArray adArray=new ADArray();
					adArray.setPos_id(pos_id);
					adArray.setAd_type(adPos.getAdType());
					//硬编码赋值
					adArray.setRender_type("1");
					// 操作数据库查询inter_type,id
					String materId = adServingMaterial.getAdMaterialId();
					ADPlan adPlan = adPlanService.selectADInterType(materId);
					adArray.setInter_type(adPlan.getInterType());
					adArray.setMaterial_type(adServingMaterial.getAdMaterialType());
					adArray.setBundle(adPlan.getBundle());
					adArray.setWidth(adServingMaterial.getWidth() + "");
					adArray.setHeight(adServingMaterial.getHeight() + "");
					//创建当前时间时间戳
					String dateTime=new Date().getTime()+"";
					//进行加密拼转换为十六进制
					String timeDes=DESUtil.byteToHexString(DESUtil.encrypt(dateTime.getBytes("UTF-8"), UtilConstants.SECRKEY));
					//对requestId进行加密
					String requestId=DESUtil.byteToHexString(DESUtil.encrypt(adAppJson.getRequest_id().getBytes("UTF-8"), UtilConstants.SECRKEY));
					//对planID进行加密
					String planId=DESUtil.byteToHexString(DESUtil.encrypt(adPlan.getAdPlanId().getBytes("UTF-8"), UtilConstants.SECRKEY));
					//点击上报连接
					String clk = UtilConstants.HTTPIP
							+ UtilConstants.HTTPPROJECT
							+ "ad_report/click?request_id="+ requestId+"&"
							+ "view_id="+timeDes+"&"
							+"inter="+adPlan.getInterType()+"&"
							+"plan="+planId+"&"
							+"clk_coord="+java.net.URLEncoder.encode("{\"req_width\":\"__REQ_WIDTH__\",\"req_height\":\"__REQ_HEIGHT__\",\"width\":\"__WIDTH__\",\"height\":\"__HEIGHT__\",\"down_x\":\"__DOWN_X__\",\"down_y\":\"__DOWN_Y__\",\"up_x\":\"__UP_X__\",\"up_y\":\"__UP_Y__\"}","UTF-8");
					adArray.setClk_link(clk);
					//转化上报连接
					String conver= UtilConstants.HTTPIP
							+ UtilConstants.HTTPPROJECT
							+ "ad_report/conver?request_id="+ requestId+"&"
							+ "view_id="+timeDes+"&"
							+ "click_id=__CLICK_ID__&action_id=__ACTION_ID__";
					adArray.setConver_link(conver);
					//曝光上报连接 
					String impress=UtilConstants.HTTPIP
							+ UtilConstants.HTTPPROJECT
							+ "ad_report/imp?request_id="+ requestId+"&"
							+ "view_id="+timeDes;
					adArray.setImpress_link(impress);
					//硬编码赋值
					adArray.setDeeplink(adPlan.getDeeplink()==null?"":adPlan.getDeeplink());
					//硬编码赋值
					adArray.setIs_full_screen("false");
					//硬编码赋值
					adArray.setHtml_segment("");
					//广告素材基本信息	
					adArray.setTitle(adServingMaterial.getAdMaterialTxt());
					adArray.setDiscript(adServingMaterial.getDescrip());
					adArray.setIconurl(adServingMaterial.getAdIconUrl());
					if (adServingMaterial.getAdMaterialType().equals("2")) {
						adArray.setVedio_url(adServingMaterial.getAdMaterialUrl());
						adArray.setVedio_dura(adServingMaterial.getPlaySeconds()+"");
					}else {
						adArray.setImgurl(adServingMaterial.getAdMaterialUrl());
					}
					ad_array.add(adArray);
				}
				adAppJson.setAd_array(ad_array);
			}else {
				adAppJson.setRet(ErrorConstants.NO_AD);
				adAppJson.setMsg("无适合广告返回");
			}
		} catch (Exception e) {
			return "{\"ret\":\""+ErrorConstants.NO_DATA+"\",\"msg\":\"系统错误\"}";
		}
		//组装JSON字符
		JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
		System.out.println(df.format(new Date())+"：完成响应拼装");
		return JSON.toJSONString(adAppJson);
	}
	/**
	 * 解析APPJSON数据
	 * @param params
	 * @return
	 * @throws Exception 
	 */
	public String analyticAppJson(String params) throws Exception{
		return null;
	}
	

	@Override
	public ADApp checkAppId(String adAppId) throws Exception {
		ADApp adApp=adAppService.selectByPrimaryKey(adAppId);
		int leng=adAppId.length();
		if (leng!=32||adApp==null||adApp.getAdAppKey()==null) 
			return null;

		return adApp;
	}
	
	@Override
	public ADPos checkPosId(String adAppId,String adPosId) throws Exception {
	ADPos adPos=adPosService.selectByPrimaryKey(adPosId);
	if (adPos==null)
		return null;
		return adPos;
	}


	@Override
	public String findMaterial(String json) throws Exception {
		 
		
		return null;
	}

	@Override
	@Transactional(rollbackFor = Exception.class) 
	public String impressCheck(String request_id, String view_id) throws Exception {
		System.out.println("接收曝光上报数据:   "+"request_id: "+request_id+" view_id: "+view_id);
		Date dateView=null;
		Map<String, String> map=new HashMap<String,String>();
		if (StringUtils.isEmpty(request_id)||StringUtils.isEmpty(view_id)) {
			map.put("ret", ErrorConstants.ERROR_REPORT_URL);
			map.put("msg", "上报链接参数错误");
			return JSON.toJSONString(map);
		}
		try {
			 //验证监报信息
			dateView=ADUtil.repCheck(request_id, view_id);
		} catch (Exception e) {
			throw new Exception(e);
		}
		Date date=new Date();
		//当前系统时间戳
		long systemDate=date.getTime();                                                                                                
		if ((systemDate-dateView.getTime())/1000 > UtilConstants.IMPRESS_SECONDS) {
			map.put("ret", ErrorConstants.TIMEOUT_REPORT);
			map.put("msg", "本次上报已过时限");
			return JSON.toJSONString(map);
		}
		//解析requestId
		String requestDes=new String(DESUtil.decrypt(DESUtil.parseHexStr2Byte(request_id), UtilConstants.SECRKEY));
		//打印数据
		System.out.println("requestId解析后的数据: "+requestDes);
		//验证requestId
		if (!ADUtil.checkRequestId(requestDes)) {
			map.put("ret", "100007");
			map.put("msg", "");
			return JSON.toJSONString(map);
		}
		//验证是否重复上报
		Map<String, String> map2=new HashMap<String,String>();
		map2.put("request_id", requestDes);
		map2.put("report_type", "1");
		int i=adReptRecordService.reportRepeat(map2);
		if (i>0){
			map.put("ret", ErrorConstants. REPEAT_REPORT);
			map.put("msg", "重复上报");
			return JSON.toJSONString(map);
		}
	    ADReptRecord adReptRecord=new ADReptRecord();
	    adReptRecord.setRequestId(requestDes);
	    adReptRecord.setResponseTime(dateView);
	    adReptRecord.setReportType("1");
	    adReptRecord.setDel("0");
	    //添加数据库
	    adReptRecordService.insert(adReptRecord);
	    map.put("ret", "0");
	    map.put("msg", "上报成功");
	    return JSON.toJSONString(map);
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(rollbackFor = Exception.class) 
	public String clickCheck(String request_id,String view_id, String inter,String plan,String clk_coord,HttpServletResponse response) throws Exception {
		//打印数据
		System.out.println("接收点击上报数据:   "+"request_id: "+request_id+" view_id: "+view_id+
				" inter: "+inter+" plan: "+plan+" clk_coord: "+clk_coord);;
		Date dateView=null;
		Map<String, Object> map=new HashMap<String,Object>();
		if (StringUtils.isEmpty(request_id)||StringUtils.isEmpty(view_id)) {
			map.put("ret", ErrorConstants.ERROR_REPORT_URL);
			map.put("msg", "上报链接参数错误");
			return JSON.toJSONString(map);
		}
		try {
			 //验证监报信息
			dateView=ADUtil.repCheck(request_id, view_id);
		} catch (Exception e) {
			throw new Exception(e);
		}
		Date date=new Date();
		//当前系统时间戳
		long systemDate=date.getTime();                                                                                                
		if ((systemDate-dateView.getTime())/1000 > UtilConstants.IMPRESS_SECONDS) {
			map.put("ret", ErrorConstants.TIMEOUT_REPORT);
			map.put("msg", "本次上报已过时限");
			return JSON.toJSONString(map);
		}
		//解析requestId
		String requestDes=new String(DESUtil.decrypt(DESUtil.parseHexStr2Byte(request_id), UtilConstants.SECRKEY));
		//打印数据
		System.out.println("requestId解析后的数据: "+requestDes);
		//验证requestId
		if (!ADUtil.checkRequestId(requestDes)) {
			map.put("ret", ErrorConstants.ERROR_REPORT_URL);
			map.put("msg", "上报链接参数错误");
			return JSON.toJSONString(map);
		}
		//正则表达式判断是否为数字
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");  
		//JSON字符串转MAP
		Map<String, String> map2=null;
		try {
			map2=JacksonUtil.toObject(clk_coord.replace("\\",""), Map.class);
			if (map2==null) {
				map.put("ret", ErrorConstants.ERROR_REPORT_URL);
				map.put("msg", "上报链接参数错误");
				return JSON.toJSONString(map);	
			}
			for (Map.Entry<String, String> entry : map2.entrySet()) {
				if (!pattern.matcher(entry.getValue()).matches()) {
					map2.put(entry.getKey(), "-888");
				}
			}
		} catch (Exception e) {
			map.put("ret", ErrorConstants.ERROR_REPORT_URL);
			map.put("msg", "上报链接参数错误");
			return JSON.toJSONString(map);
		}
		//验证是否重复上报
		Map<String, String> repotMap=new HashMap<String,String>();
		repotMap.put("request_id", requestDes);
		repotMap.put("report_type", "2");
		int i=adReptRecordService.reportRepeat(repotMap);
		if (i>0){
			map.put("ret", ErrorConstants. REPEAT_REPORT);
			map.put("msg", "重复上报");
			return JSON.toJSONString(map);
		}
		//生产20位clickid变量
		String clickId=ADUtil.getItemID(20);
		ADReptRecord adReptRecord=new ADReptRecord();
	    adReptRecord.setRequestId(requestDes);
	    adReptRecord.setResponseTime(dateView);
	    adReptRecord.setClickId(clickId);
	    adReptRecord.setClickCoord(JSON.toJSONString(map2));
	    adReptRecord.setReportType("2");
	    adReptRecord.setDel("0");
	    //添加数据库
	    adReptRecordService.insert(adReptRecord);
	    //对plan进行解码
	    String adPlanId=new String(DESUtil.decrypt(DESUtil.parseHexStr2Byte(plan), UtilConstants.SECRKEY));
	    //打印数据
	    System.out.println("plan解析后的数据: "+adPlanId);
	    ADPlan adPlan=adPlanService.selectByPrimaryKey(adPlanId);
	    //组装JSON中data数据
	    Map<String, String> data=null;
	    if (inter.equals("0")) {
	    	response.setStatus(302);
	    	response.setHeader("Location", "http://"+adPlan.getTargetUrl());
	    	return null;
		}else {
			data=new HashMap<String,String>();
			data.put("distlink", adPlan.getTargetUrl());
			data.put("clickid", clickId);
		}
	    map.put("ret", "0");
	    map.put("data",data);
		return JSON.toJSONString(map);
	}

	@Override
	@Transactional(rollbackFor = Exception.class) 
	public String converCheck(String request_id, String view_id, String click_id,String action_id)
			throws Exception {
		System.out.println("接收转化上报数据:   "+"request_id: "+request_id+" view_id: "+view_id+
				" click_id: "+click_id+" action_id: "+action_id);
		Map<String, String> map=new HashMap<String,String>();
		if(StringUtils.isEmpty(request_id) || StringUtils.isEmpty(view_id) || StringUtils.isEmpty(click_id)){
			map.put("ret", ErrorConstants.ERROR_REPORT_URL);
			map.put("msg", "上报链接参数错误");
			return JSON.toJSONString(map);
		}
		Date dateView=null;
		try {
			 //验证监报信息
			dateView=ADUtil.repCheck(request_id, view_id);
		} catch (Exception e) {
			throw new Exception(e);
		}
		Date date=new Date();
		//当前系统时间戳
		long systemDate=date.getTime();                                                                                                
 		if ((systemDate-dateView.getTime())/1000 > UtilConstants.IMPRESS_SECONDS) {
			map.put("ret", ErrorConstants.TIMEOUT_REPORT);
			map.put("msg", "本次上报已过时限");
			return JSON.toJSONString(map);
		}	
		//解析requestId
		String requestDes=new String(DESUtil.decrypt(DESUtil.parseHexStr2Byte(request_id), UtilConstants.SECRKEY));
		 //打印数据
	    System.out.println("requestId解析后的数据: "+requestDes);
		//验证requestId
		if (!ADUtil.checkRequestId(requestDes)) {
			map.put("ret", ErrorConstants.ERROR_REPORT_URL);
			map.put("msg", "上报链接参数错误");
			return JSON.toJSONString(map);
		}
		//查询数据匹配
		int i=0;
		Map<String, String> repotMap=new HashMap<String,String>();
		repotMap.put("request_id", requestDes);
		repotMap.put("report_type", "2");
		repotMap.put("click_id", click_id);
		i=adReptRecordService.reportRepeat(repotMap);
		if (i<0) {
			map.put("ret", ErrorConstants.ERROR_REPORT_URL);
			map.put("msg", "上报链接参数错误");
			return JSON.toJSONString(map);
		}
		//验证是否重复上报
		repotMap.put("request_id", requestDes);
		repotMap.put("report_type", "3");
		repotMap.put("click_id", click_id);
		repotMap.put("action_id",action_id);
		i=adReptRecordService.reportRepeat(repotMap);
		if (i>0){
			map.put("ret", ErrorConstants. REPEAT_REPORT);
			map.put("msg", "重复上报");
			return JSON.toJSONString(map);
		}
		ADReptRecord record=new ADReptRecord();
		record.setRequestId(requestDes);
		record.setResponseTime(dateView);
		record.setClickId(click_id);
		record.setActionId(action_id);
		record.setReportType("3");
		record.setDel("0");
		 //添加数据库
	    adReptRecordService.insert(record);
	    map.put("ret", "0");
	    return JSON.toJSONString(map);
	}
}
